const autoprefixer = require('autoprefixer')
// const pxtorem = require('postcss-pxtorem')
const path = require('path')
const FileManagerPlugin = require('filemanager-webpack-plugin')
const version = 'R1.0.2'
const versionTime = new Date().getTime()

function resolve(dir) {
  return path.join(__dirname, dir)
}

function dateToTimeStr(date) {
  const yyyy = date.getFullYear()
  const mth = dateNum2Str(date.getMonth() + 1)
  const dd = dateNum2Str(date.getDate())
  const hh = dateNum2Str(date.getHours())
  const mm = dateNum2Str(date.getMinutes())
  const ss = dateNum2Str(date.getSeconds())
  return `${yyyy}-${mth}-${dd} ${hh}:${mm}:${ss}`
}
// 返回当前时间标准字符串 yyyyMMddhhmmss 20180514153320
function getNowDateTimeShortStr() {
  return dateToTimeStr(new Date()).replace(/[\s|\s*-\s*|:]/g, '')
}

function dateNum2Str(num) {
  if (num < 10) {
    return '0' + num
  } else {
    return num + ''
  }
}

module.exports = {
  outputDir: 'dist',
  productionSourceMap: false,
  publicPath: process.env.NODE_ENV === 'production' ? './' : '/',
  parallel: false,
  css: {
    loaderOptions: {
      sass: {
        additionalData: `@import "@styles/global.scss";`,
      },
      postcss: {
        plugins: [
          autoprefixer(),
          // pxtorem({
          //   rootValue: 75,
          //   propList: ['*'],
          //   selectorBlackList: ['van'],
          // }),
        ],
      },
    },
    extract: {
      // 打包后的css加版本号。
      filename: `css/[name].${version}.${versionTime}.css`,
      chunkFilename: `css/[name].${version}.${versionTime}.css`,
    },
  },
  chainWebpack: config => {
    config.resolve.alias
      .set('@$', resolve('./src'))
      .set('@images', resolve('./src/assets/images'))
      .set('@styles', resolve('./src/assets/styles'))
      .set('@com', resolve('./src/components'))
      .set('@api', resolve('./src/api'))
      .set('@common', resolve('./src/common'))
  },
  configureWebpack: config => {
    config.output.filename = `js/[name].${version}.${versionTime}.js`
    config.output.chunkFilename = `js/[name].${version}.${versionTime}.js`

    config.module.rules.push({
      test: /\.worker\.js$/,
      loader: 'worker-loader',
      exclude: /node_modules/,
      options: {
        inline: 'fallback',
      },
    })
    config.plugins.push(
      new FileManagerPlugin({
        events: {
          onEnd: [
            {
              mkdir: ['./release'],
              archive: [
                {
                  source: './dist',
                  destination: `./release/pskh-${getNowDateTimeShortStr()}${version}.zip`,
                },
              ],
            },
          ],
        },
      })
    )
  },
  transpileDependencies: ['sm-crypto'],
}
